import { Input, type InputRef } from "antd";
import React, { forwardRef, useState, useEffect, useRef } from "react";
import "./MikuInput.css";

interface MikuInputProps extends Omit<React.ComponentProps<typeof Input>, 'onChange' | 'value'> {
  inputType?: 'string' | 'number';
  precision?: number; // 数字输入的精度，可选 
  value?: string | number;
  onChange?: (value: string) => void;
  onHistory?: (value: string[]) => void;
  expiryTime?: number; // 数据历史记录的过期时间，可选
}

function isNumberStringOrEmpty(str: string): boolean {
  const trimmed = str.trim();
  if (trimmed === '') {
    return true;
  }

  const numberRegex = /^-?(\d+(\.\d*)?|\.\d+)$/;
  return numberRegex.test(trimmed);
}

export const MikuInput = forwardRef<InputRef, MikuInputProps>(
  ({ value, onChange, onBlur, onHistory, expiryTime, inputType = 'string', precision, placeholder, ...restProps }, ref) => {
    const [inputValue, setInputValue] = useState<string>(
      value !== undefined ? String(value) : ''
    );
    const [statePlaceholder, setStatePlaceholder] = useState<string>(placeholder || "");
    const [historyValue, setHistoryValue] = useState<string[]>([]);
    const clearTimerRef = useRef<NodeJS.Timeout | null>(null);

    // 同步外部传入的value变化
    useEffect(() => {
      if (value !== undefined) {
        setInputValue(String(value));
      }
    }, [value]);

    // 清除历史记录
    const clearHistory = () => {
      if (historyValue.length > 0) {
        setHistoryValue([]);
        onHistory?.([]);
      }
      if (clearTimerRef.current) {
        clearTimeout(clearTimerRef.current);
        clearTimerRef.current = null;
      }
    };

    // 设置定时清除
    const setupAutoClear = (intervalMs?: number) => {
      if (clearTimerRef.current) {
        clearTimeout(clearTimerRef.current);
        clearTimerRef.current = null;
      }

      if (!intervalMs || intervalMs <= 0) {
        return;
      }

      clearTimerRef.current = setTimeout(clearHistory, intervalMs);
    };

    // 当expiryTime变化时设置定时清除
    useEffect(() => {
      setupAutoClear(expiryTime);

      return () => {
        if (clearTimerRef.current) {
          clearTimeout(clearTimerRef.current);
          clearTimerRef.current = null;
        }
      };
    }, [expiryTime]);

    // 处理输入变化
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      const newValue = e.target.value;
      setInputValue(newValue);
      onChange?.(newValue);
    };

    // 失去焦点时处理
    const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
      if (inputType === 'number') {
        const isNum = isNumberStringOrEmpty(inputValue);
        if (!isNum) {
          const emptyValue = '';
          setInputValue(emptyValue);
          setStatePlaceholder("不是合法的数字...");
          onChange?.(emptyValue);
        } else {
          if (inputValue !== '') {
            // 处理数字精度
            const processedValue = precision 
              ? parseFloat(inputValue).toFixed(precision) 
              : inputValue;
            
            // 检查内容是否有变动（与最后一条历史记录比较）
            const hasChanged = historyValue.length === 0 
              || historyValue[historyValue.length - 1] !== processedValue;
            
            if (hasChanged) {
              // 内容有变动，更新历史记录并触发回调
              const newHistory = [...historyValue, processedValue];
              setHistoryValue(newHistory);
              onHistory?.(newHistory);
            }
            
            // 无论内容是否变动，都重新设置定时清除
            if (expiryTime && expiryTime > 0) {
              setupAutoClear(expiryTime);
            }
            
            // 更新输入框显示的精确值
            setInputValue(processedValue);
          }
          setStatePlaceholder(placeholder || "");
        }
      } else {
        if (inputValue !== '') {
          // 检查内容是否有变动（与最后一条历史记录比较）
          const hasChanged = historyValue.length === 0 
            || historyValue[historyValue.length - 1] !== inputValue;
          
          if (hasChanged) {
            // 内容有变动，更新历史记录并触发回调
            const newHistory = [...historyValue, inputValue];
            setHistoryValue(newHistory);
            onHistory?.(newHistory);
          }
          
          // 无论内容是否变动，都重新设置定时清除
          if (expiryTime && expiryTime > 0) {
            setupAutoClear(expiryTime);
          }
        }
      }
      onBlur?.(e);
    };

    return (
      <div className="miku-input-wrapper">
        <Input
          className="miku-input"
          ref={ref}
          value={inputValue}
          onChange={handleChange}
          onBlur={handleBlur}
          placeholder={statePlaceholder}
          {...restProps}
        />
      </div>
    );
  }
);

MikuInput.displayName = "MikuInput";
